# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
""" """
import yaml
import time
import os
from playwright.sync_api import Page, expect

# 获取当前文件的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 项目根目录是当前文件目录上一级
project_root = os.path.abspath(os.path.join(current_dir, ".."))
# 截图保存目录
screenshot_dir = os.path.join(project_root, "screenshot")


def read_yaml(config_name: str) -> dict:
    """读取yaml文件"""
    # 配置文件路径
    config_path = os.path.join(project_root, "config", config_name)
    with open(config_path, encoding="utf-8") as f:
        config = yaml.safe_load(f)
    return config


def get_now_time():
    now_time = time.strftime("%Y%m%d%H%M%S")
    return now_time


def mkdir(parent_dir, child_dir_name):
    """查看指定目录下是否存在指定名称的子目录，不存在则创建子目录"""
    # 拼接完整的目录路径
    full_path = os.path.join(parent_dir, child_dir_name)
    # 检查目录是否存在
    if not os.path.exists(full_path):
        # 如果目录不存在，则创建目录
        os.makedirs(full_path)
    return full_path


def reload_wait(
    page: Page, parent_element: str, child_element: str, max_wait=12, wait_interval=5000
):
    """页面刷新等待父元素下的子元素出现"""

    def wait_for_child_element_appears():
        status_elements = page.locator(parent_element)
        for x in range(status_elements.count()):
            if not status_elements.nth(x).locator(child_element).is_visible():
                return False
        return True

    # 刷新页面等待元素出现
    for y in range(max_wait):
        result = wait_for_child_element_appears()
        if result:
            break
        else:  # 等待一段时间再刷新页面,查看录音是否都上线了
            page.wait_for_timeout(wait_interval)
            page.reload()


if __name__ == "__main__":
    print(screenshot_dir)
